package com.origin.sse.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.IdUtil;
import com.origin.sse.service.SseEmitterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author yezh
 * @date 2024/1/15 19:23
 */
@RestController
public class SseEmitterController {

    @Autowired
    private SseEmitterService sseEmitterService;

    /**
     * 创建 SSE 长链接
     * 必须返回 SseEmitter, 告诉浏览器这是一个 event-stream
     **/
    @GetMapping(value = "/CreateSseConnect")
    public SseEmitter createSseConnect(@RequestParam(name = "event_types") String eventTypes) {
        return sseEmitterService.getSseConn(IdUtil.simpleUUID(), CharSequenceUtil.split(eventTypes, StrPool.COMMA));
    }

    @GetMapping("/SendData")
    public void sendData(@RequestParam("event_type") String eventType) {
        sseEmitterService.sendMsgToClient(DateUtil.now(), eventType);
    }

    /**
     * 关闭 SSE 连接
     **/
    @GetMapping("/CloseSseConnect")
    public void closeSseConnect(@RequestParam("clientId") String clientId) {
        sseEmitterService.closeSseConnect(clientId);
    }

}
